
#include "beepled.h"

#define ZQ 60000

#define ON  0
#define OFF 1

#define DO 2300
#define RE 1150
// #define MI 1703
// #define FA 1703
// #define SO 1703
// #define LA 1703
// #define XI 1703

char buf1[2];
char buf2[2];
char buf3[2];
char buf4[2];



void close_ledfd(void *arg) {

	printf("s\n");
	buf1[0] = 0; 
	buf2[0] = 0; 
	buf3[0] = 0; 
	buf4[0] = 0; 

	buf1[1] = 7;
	buf2[1] = 9;
	buf3[1] = 8;
	buf4[0] = 0; 
	buf4[1] = 10;
	write(*(int *)arg,buf1,sizeof(buf1));
	write(*(int *)arg,buf2,sizeof(buf2));
	write(*(int *)arg,buf3,sizeof(buf3));
	write(*(int *)arg,buf4,sizeof(buf4));
	usleep(10000);	
	recvled = false;
    close(*(int *)arg); // 关闭文件描述符
}

int lighton(void)
{
	printf("&&&&&&&&&&&&&&openled\n");
	recvled = true;
	//1.打开文件
	int fd = open("/dev/led_drv",O_RDWR);
	if(fd == -1)
	{
		perror("open");
		return -1;
	}

	pthread_cleanup_push(close_ledfd, (void *)&fd); // 注册关闭文件的清理函数

	//2.利用与驱动程序相同的接口，来达到调用驱动程序的接口效果
	while(1)
	{

		buf1[0] = 1; //开灯
		buf1[1] = 7;
		buf2[0] = 1; //开灯
		buf2[1] = 9;
		write(fd,buf1,sizeof(buf1));
		write(fd,buf2,sizeof(buf2));

		usleep(ZQ);
		
		buf1[0] = 0; 
		buf1[1] = 7;
		buf2[0] = 0; 
		buf2[1] = 9;
		write(fd,buf1,sizeof(buf1));
		write(fd,buf2,sizeof(buf2));
		buf3[0] = 1; 
		buf3[1] = 8;
		buf4[0] = 1; 
		buf4[1] = 10;
		write(fd,buf3,sizeof(buf3));
		write(fd,buf4,sizeof(buf4));

		usleep(ZQ);

		buf3[0] = 0; 
		buf3[1] = 8;
		buf4[0] = 0; 
		buf4[1] = 10;
		write(fd,buf3,sizeof(buf3));
		write(fd,buf4,sizeof(buf4));

		usleep(ZQ);
	}

	pthread_cleanup_pop(1); 
	// recvled = false;
	// pthread_exit(NULL);
}


void close_beepfd(void *arg) 
{
	ioctl(*(int *)arg, OFF, 1);
	close(*(int *)arg);
}


int beepon(void)
{
	// 打开蜂鸣器
	int fd = open("/dev/beep", O_RDWR);
	if(fd == -1)
	{
		perror("open:");
		exit(0);
	}
	
	pthread_cleanup_push(close_beepfd, (void *)&fd); // 注册关闭文件的清理函数

 	int i;
	while(1)
	{
		// int i;
		// for(i=0;i<50;i++)
		i = 100000;
		while(1)
		{
			// 使能蜂鸣器
			ioctl(fd, ON, 1);
			usleep(100000-i);

			// 关闭蜂鸣器
			ioctl(fd, OFF, 1);
			usleep(i);
			i--;
			if(i==0)
				break;
		}
		// }
		// for(i=0;i<50;i++)
		// {
		// 	// 使能蜂鸣器
		// 	ioctl(fd, ON, 1);
		// 	usleep(DO);

		// 	// 关闭蜂鸣器
		// 	ioctl(fd, OFF, 1);
		// 	usleep(DO);
		// }

	}

	pthread_cleanup_pop(1);
	
	// close(fd);
	// return 0;
}

